# THIS FILE IS A PART OF VCStudio
# PYTHON 3

# This a console project manager.

import os

# GTK module ( Graphical interface
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import GLib
from gi.repository import Gdk
import cairo

# Own modules
from settings import settings
from settings import talk
from settings import fileformats
from project_manager import pm_project

#UI modules
from UI import UI_elements
from UI import UI_color

# Studio
from studio import checklist

def layer(win, call):
    
    # Making the layer
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, win.current['w'],
                                                      win.current['h'])
    layer = cairo.Context(surface)
    
    
    #text setting
    layer.select_font_face("Monospace", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
    
    UI_color.set(layer, win, "dark_overdrop")
    layer.rectangle(
        0,
        0,
        win.current["w"],
        win.current["h"],
        )
    layer.fill()
    
    
    UI_color.set(layer, win, "node_background")
    UI_elements.roundrect(layer, win, 
        40,
        40,
        win.current["w"]-80,
        win.current["h"]-80,
        10)
    
    ############################################################################
    
    # This dialogue deals with file selection. This is not the only place where
    # files are drawn. So don't rely on this dialog only. 
    
    # To make all the files drawn first off all I want to get all the files data
    # and later to clean it. The problem is that it's running on every frame so
    # some particular cleverness is required.
    
    # I do want to clean after the dialog is closed so if a change in the files
    # happened it could be loaded on the next loading of this window. 
    
    # On the other hand reading all the file dynamically would not be wise because
    # of expected volume of those files. For things like textures folder in the 
    # assets it could be possible. But here it will look through the entire 
    # project. With all the renders of all of the shots from all of the scenes. 
    # Imagine a movie that is 2 hour long and it's a good 24 frames per second.
    # Each of which has 4 versions saved in different folders. This is not the
    # kind of data I would try to load dynamically. Unless you know a clever
    # way to do so. Please tell me so if you do.
    
    ############################################################################
    
    
    if "AllFiles" not in win.current:
        
        win.current["AllFiles"] = []
        for r, d, f in sorted(os.walk(win.project)):
            for item in f:
                win.current["AllFiles"].append(os.path.join(r, item).replace(win.project, ""))
        
    
    # Now that we have the files. There should be some way to filter them.
    # I guess let's add a searchbox and buttons on the side for filtering. 
    
    if "file_selector" not in win.current:
        win.current["file_selector"] = {
            "image"  :True,
            "blender":False,
            "video"  :True,
            "file"   :False,
            "chr"    :True,
            "veh"    :True,
            "loc"    :True,
            "obj"    :True,
            "vse"    :False,
            "folder" :False
            }
    
    
    ############### TOP PANEL ###################
    
    # Left Icons
    
    for num, thing in enumerate(win.current["file_selector"]):
        
        if num > 3:
            num = num + 1
        
        if win.current["file_selector"][thing]:
            
            UI_color.set(layer, win, "progress_time")
            UI_elements.roundrect(layer, win,
                50+(40*num),
                50, 
                40,
                40,
                10)
            
        def do():
            win.current["file_selector"][thing] = not win.current["file_selector"][thing]
        
        UI_elements.roundrect(layer, win,
            50+(40*num),
            50, 
            40,
            40,
            10,
            do,
            thing)
        
        
    # Search
    
    UI_elements.image(layer, win, "settings/themes/"\
        +win.settings["Theme"]+"/icons/search.png", 
        win.current["w"]-440,
        50, 
        40,
        40)
    
    UI_elements.text(layer, win, "file_select_search",
        win.current["w"]-400,
        50,
        350,
        40)
    
    
    ##### BOTTOM BUTTONS ####
    
    def do():
        filechooser = Gtk.FileChooserDialog(talk.text("select_file"),
                                         None,
                                         Gtk.FileChooserAction.OPEN,
                                        (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                                        Gtk.STOCK_OPEN, Gtk.ResponseType.OK))
        filechooser.set_default_response(Gtk.ResponseType.OK)
        response = filechooser.run()
        if response == Gtk.ResponseType.OK:
            get = filechooser.get_filename()
            
            win.current["calls"][call]["var"] = get 
        
            del win.current["AllFiles"]
            
        filechooser.destroy()
    
    UI_elements.roundrect(layer, win, 
        win.current["w"]-120,
        win.current["h"]-80,
        40,
        40,
        10,
        button=do,
        icon="folder",
        tip=talk.text("outside_folder"))
    
    def do():
        win.current["calls"][call]["var"] = False 
        
        del win.current["AllFiles"]
        
    UI_elements.roundrect(layer, win, 
        win.current["w"]-80,
        win.current["h"]-80,
        40,
        40,
        10,
        button=do,
        icon="cancel",
        tip=talk.text("cancel"))
    
    # Short cut ESC
    if 65307 in win.current["keys"] and not win.textactive:
        do()    
    
    # Now let's prepare the ground for the next part. 
    
    UI_elements.roundrect(layer, win, 
        50,
        100,
        win.current["w"]-100,
        win.current["h"]-200,
        10,
        fill=False)
    layer.clip()
    
    
    
    ### ACTUALL FILES LIST ###
    
    tileX = 70
    current_Y = 0
    
    if "file_select" not in win.scroll:
        win.scroll["file_select"] = 0
    
    if "AllFiles" in win.current: 
        for filename in win.current["AllFiles"]:
            
            ######################## FILTERING STARTS ##########################
            
            okay = True
            
            # By search            
            
            for stuff in win.text["file_select_search"]["text"].split(" "):
                if stuff:
                    if stuff.lower() not in filename.lower():
                        okay = False
            
            # By folder
            folderfound = False
            
            if okay and "chr/" in filename:
                folderfound = True
                if not win.current["file_selector"]["chr"]:
                    okay = False
            
            if okay and "veh/" in filename:
                folderfound = True
                if not win.current["file_selector"]["veh"]:
                    okay = False
            
            if okay and "loc/" in filename:
                folderfound = True
                if not win.current["file_selector"]["loc"]:
                    okay = False
            
            if okay and "obj/" in filename:
                folderfound = True
                if not win.current["file_selector"]["obj"]:
                    okay = False
            
            if okay and "rnd/" in filename:
                folderfound = True
                if not win.current["file_selector"]["vse"]:
                    okay = False
            
            if okay and not folderfound:
                if not win.current["file_selector"]["folder"]:
                    okay = False
            
            # By filetype
            
            typefound = False
            
            if okay:
                
                # Images
                for f in fileformats.images:
                    if filename.endswith(f):
                        typefound = True
                        thecoloris =  "node_imagefile"
                        if not win.current["file_selector"]["image"]:
                            okay = False
                        break
            if okay:
                
                # Videos
                for f in fileformats.videos:
                    if filename.endswith(f):
                        typefound = True
                        thecoloris =  "node_videofile"
                        if not win.current["file_selector"]["video"]:
                            okay = False
                        break
            if okay:
                
                # Blend Files
                if filename.endswith(".blend"):
                    typefound = True
                    thecoloris =  "node_blendfile"
                    if "ast/" in filename:
                        thecoloris =  "node_asset"
                    if not win.current["file_selector"]["blender"]:
                        okay = False
            
            if okay:
                
                if typefound == False:
                    thecoloris =  "node_script"
                    if not win.current["file_selector"]["file"]:
                        okay = False
                    
            
            ######################### FILTERING END ############################            
            
            if okay:
                
                
                
                if int(current_Y + win.scroll["file_select"] + 100) in range(0-100, win.current["h"]):
                    
                    # Making the layer
                    nodesurface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 170, 200)
                    node = cairo.Context(nodesurface)
                    node.select_font_face("Monospace", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
                    
                    
                    UI_elements.roundrect(node, win, 
                        0,
                        0,
                        170,
                        200,
                        10,
                        fill=False)
                    
                    node.clip()
                    
                    # Background
                    UI_color.set(node, win, "dark_overdrop")
                    node.rectangle(0,0,170, 200)
                    node.fill()
                    
                    # Banner
                    UI_color.set(node, win, thecoloris) 
                    node.rectangle(0,0,170, 20)
                    node.fill()
                    
                    # Outputting the layer
                    layer.set_source_surface(nodesurface, 
                            tileX-10,
                            current_Y + win.scroll["file_select"] + 120)
                    layer.paint()
                    
                    UI_elements.image(layer, win, win.project+filename, 
                        tileX,
                        current_Y + win.scroll["file_select"] + 150, 
                        150,
                        150)
                    
                    # If this is a checklist
                    
                    if filename.endswith(".progress"):
                        
                        fraction = checklist.get_fraction(win, filename)
                        
                        UI_color.set(layer, win, "progress_background")
                        UI_elements.roundrect(layer, win,
                            tileX,
                            current_Y + win.scroll["file_select"] + 300, 
                            150,
                            0,
                            5)
                        
                        UI_color.set(layer, win, "progress_active")
                        UI_elements.roundrect(layer, win,
                            tileX,
                            current_Y + win.scroll["file_select"] + 300, 
                            150*fraction,
                            0,
                            5)
                        
                        
                UI_color.set(layer, win, "text_normal")
                layer.set_font_size(12)
                layer.move_to(tileX,
                    current_Y + win.scroll["file_select"] + 135)
                layer.show_text(filename[filename.rfind("/")+1:][:22])
                
                
                # Button to activate it
                def do():
                    win.current["calls"][call]["var"] = filename
                
                layer.set_line_width(4)    
                UI_elements.roundrect(layer, win, 
                    tileX-10,
                    current_Y + win.scroll["file_select"] + 120,
                    170,
                    200,
                    10,
                    button=do,
                    tip=filename,
                    fill=False,
                    clip=[
                            50,
                            100,
                            win.current["w"]-100,
                            win.current["h"]-200
                            ])
                
                layer.stroke()
                layer.set_line_width(2) 
                
                tileX += 200
                
                if tileX > win.current["w"]-220:
                    tileX = 70
                    
                    current_Y += 230
    
    
    current_Y += 230
    
    UI_elements.scroll_area(layer, win, "file_select", 
        50,
        100,
        win.current["w"]-100,
        win.current["h"]-200,
        current_Y,
        bar=True,
        mmb=True,
        url="file_select",
        strenght=130
        )
    
    
    
    return surface
